#pragma once

#include <iostream>
#include <string>
#include <cstring>

#include "Log.hpp"
#include "Dict.hpp"

Dict dict;

class Task
{
private:
    int sockfd_;
    std::string clientip_;
    uint16_t clientport_;

public:
    Task(int sockfd, const std::string &clientip, const uint16_t &clientport)
        : sockfd_(sockfd), clientip_(clientip), clientport_(clientport)
    {
    }
    Task()
    {
    }
    ~Task()
    {
    }

public:
    void operator()()
    {
        Run();
    }

private:
    void Run()
    {
        // cs
        // Tcp是面向字节流的，你怎么保证，你读取上来的数据，是"一个" "完整" 的报文呢？
        char buffer[SIZE];
        while (true)
        {
            memset(buffer, 0, sizeof(buffer));
            ssize_t n = read(sockfd_, buffer, sizeof(buffer));
            std::cout << "n: " << n << std::endl;
            if (n > 0)
            {
                buffer[n] = 0;
                std::cout << "client key@ " << buffer << std::endl;

                // 服务器处理信息
                std::string echo_string = dict.translation(buffer);
                n = write(sockfd_, echo_string.c_str(), echo_string.size());
                if (n < 0)
                {
                    lg(Warning, "write error, errno: %d, errstring: %s", errno, strerror(errno));
                }
                lg(Info, "server write success...");
            }
            else if (n == 0)
            {
                lg(Info, "%s-%d Client Quit..., server close sockfd: %d", clientip_.c_str(), clientport_, sockfd_);
            }
            else
            {
                lg(Warning, "read error,sockfd: %d, client ip: %s, client port: %d", sockfd_, clientip_.c_str(), clientport_);
            }
        }

        close(sockfd_);
    }
};
